package com.hnhcyy.goods.service.impl;

import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.hnhcyy.goods.mapper.GoodsPreMapper;
import com.hnhcyy.goods.pojo.GoodsPre;
import com.hnhcyy.goods.service.GoodsPreAdminService;

/**
 * 即将到货service实现类
 * 
 * @author Administrator
 *
 */
@Service
public class GoodsPreAdminServiceImpl implements GoodsPreAdminService {

	@Autowired
	GoodsPreMapper goodsPreMapper;

	public static final ObjectMapper MAPPER = new ObjectMapper();

	/**
	 * 获取即将到货商品列表
	 */
	@Override
	public String listGoodsPre(GoodsPre queryParam) {

		System.out.println("-=-=-=-" + queryParam.toString());

		List<GoodsPre> list = goodsPreMapper.listGoodsPre(queryParam);

		// 转化为json字符串返回，因为admin端调用用的是原生feign，直接返回List和Mapper会提示解码错误

		String result = "";
		try {
			result = MAPPER.writeValueAsString(list);
		} catch (JsonProcessingException e) {
			e.printStackTrace();
		}

		System.out.println("---->" + result);

		return result;

	}

	/**
	 * 新增即将到货
	 */
	@Override
	public String insertGoodsPre(GoodsPre goodsPre) {
		
		String newId = getNewId();
		
		goodsPre.setSpid(newId);
		
		System.out.println("pre--------" + goodsPre.toString());
		
		int addResult = goodsPreMapper.insertGoodsPre(goodsPre);

		return addResult + "";
	}
	
	/**
	 * 更新即将到货
	 */
	@Override
	public String updateGoodsPre(GoodsPre goodsPre) {
		
		int updateResult = goodsPreMapper.updateGoodsPre(goodsPre);
		return updateResult + "";
	}
	
	/**
	 * 删除即将到货信息
	 */
	@Override
	public String deleteGoodsPre(String spid){
		
		int deleteResult = goodsPreMapper.deleteGoodsPre(spid);
		
		return deleteResult + "";
	}

	/**
	 * 获取新ID
	 * 
	 * @return
	 */
	private String getNewId() {
		// 获取最大spid
		String maxSpid = goodsPreMapper.selectMaxSpid();
		// 获取当前ID的字符位的值 如 TMP001 的TMP
		String idStr = maxSpid.substring(0, 3);
		// 获取id的数字位 如 TMP001 的 001
		String idNum = maxSpid.substring(3, maxSpid.length());
		int num = Integer.valueOf(idNum);
		int max = num + 1;
		
		if (999 < max){
			//超过999,则修改字符位
			char[] chars = idStr.toCharArray();
			int len = chars.length;
			//用于结束while循环
			boolean isEnd = false;
			//超过Z则修改前一位
			while (!isEnd){
				if ('Z' == chars[len - 1]){
					len -- ;
				}else {
					chars[len - 1] ++;
					max = 1;
					isEnd = true;
				}
			}
			//再转为String
			idStr = chars.toString();
		}
		
		//max转华为String 并补0
		String maxStr = max + "";
		while (3 < maxStr.length()){
			maxStr = "0" + maxStr;
		}
		
		String newId = idStr + maxStr;
		return newId;

	}

}
